package com.litorg.demo.db.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.nio.reactor.IOReactorException;
import org.opentsdb.client.OpenTSDBClient;
import org.opentsdb.client.OpenTSDBClientFactory;
import org.opentsdb.client.OpenTSDBConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.Objects;

/**
 * OpenTSDB客户端初始化
 *
 * @author cw
 * @date 2022/06/20
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "assembly-switch", name = "opentsdb", havingValue = "true")
public class OpenTSDBConfiguration {

    @Value("${opentsdb.address.host:}")
    private String host;

    @Value("${opentsdb.address.port:}")
    private Integer port;

    private OpenTSDBClient openTSDBClient;

    @Bean("openTSDBClient")
    public OpenTSDBClient getOpenTSDBClient() throws IOReactorException {
        OpenTSDBConfig config = OpenTSDBConfig.address(host, port).config();
        OpenTSDBClient client = OpenTSDBClientFactory.connect(config);
        openTSDBClient = client;
        log.info("OpenTSDB客户端启动，成功");
        return client;
    }

    @PreDestroy
    public void shutDownOpenTSDBClient() {
        if (!Objects.isNull(openTSDBClient)) {
            try {
                openTSDBClient.gracefulClose();
                log.info("OpenTSDB客户端销毁，成功");
            } catch (IOException e) {
                log.error("OpenTSDB客户端销毁，异常", e);
            }
        }
    }
}